package com.sy.cloud.guess.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gok.pay.wx.SignType;
import com.gok.pay.wx.WXPayUtil;
import com.google.gson.Gson;
import com.sy.cloud.guess.model.Gokguessnum;
import com.sy.cloud.guess.model.Qwuser;
import com.sy.cloud.wechat.entity.UserAccessToken;
import com.sy.cloud.wechat.entity.WeChatUserInfo;
import com.sy.cloud.wechat.model.WechatUser;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.cloud.wechat.service.AuthorizeService;
import com.sy.cloud.wechat.service.ConfigService;
import com.sy.common.model.Juejinuser;
import com.sy.common.persistence.QueryHelper;
import com.sy.common.service.IBaseService;
import com.sy.common.service.ITestService;
import com.sy.common.util.DatabaseContextHolder;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;

/**
 * Created by zhuwenquan on 2017/9/11.
 * 默认首页
 */
@Controller
@Slf4j
public class IndexController {

    @Resource
    private IBaseService baseService;
    @Resource
    private ITestService testService;

    @Resource
    private TradeController tradeController;

    @Resource
    private CookieController cookieController;

    private AuthorizeService authorizeService = new AuthorizeService();

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String index( HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        // 获取公众号授权，把获取到的openid存储到session中
        Wxuser wxuser = new Wxuser();
        String openId = request.getParameter("open_id");
        String tokenstr = "";
        if( openId!= null ){
            log.info("把openId存储到cookie");
            cookieController.addCookie(response, "openId", openId);

        }else{
            log.info("get参数中没有openId");
            String code = request.getParameter("code");
            tokenstr = request.getParameter("token");
            wxuser = testService.getWx(tokenstr);
            if( code == null ) {
                log.info("去获取code");
                // 参数中没有open_id，那么就去找token。可以根据token找到appid和appsecret,然后获取授权，获得用户的头像昵称

                if (tokenstr != null) {
                    log.info("get参数中有token值");
                    request.getSession().setAttribute("token", tokenstr);
                    if( wxuser != null ){
                        log.info("去获取公众号授权");
                        String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "?" + request.getQueryString();

                        String contex = request.getContextPath();
                        log.info("context" + contex);
                        // 获取公众号授权
                        String returnUrl = authorizeService.getAuthorizeUserInfoUrl(wxuser.getAppid(), url, "1");

                        try {
                            response.sendRedirect(returnUrl);
                        } catch (IOException e) {
                            response.getWriter().print(e.toString());
                            e.printStackTrace();
                        }
                    }
                }
            }else{
                // 有code值
                if( request.getSession().getAttribute("headimg") != null ){
                    request.setAttribute("headimg", request.getSession().getAttribute("headimg"));
                    request.setAttribute("nickname", request.getSession().getAttribute("nickname"));
                }else{
                    wxuser = testService.getWx(request.getParameter("token"));
                    Gson gson = new Gson();
                    try{
                        UserAccessToken userAccessToken = authorizeService.getUserAccessTokenByCode( wxuser.getAppid(), wxuser.getAppsecret(), code );
                        log.info(gson.toJson(userAccessToken));
//                authorizeService.getWeChatUnSubscribeUserInfo( wxuser.getAccessToken(), userAccessToken.getOpenid());
                        // 把openid存储到session中
                        request.getSession().setAttribute("openId", userAccessToken.getOpenid());
                        try{
                            // 需要网页授权access_token
                            WeChatUserInfo w = authorizeService.getWeChatUnSubscribeUserInfo(userAccessToken.getAccess_token(), userAccessToken.getOpenid());
                            request.setAttribute("headimg", w.getHeadimgurl());
                            request.setAttribute("nickname",w.getNickname());
                            String headimg = w.getHeadimgurl();
                            headimg = headimg.substring( 0,headimg.length()-3 );
                            log.info("设置headimg"+headimg);
                            request.getSession().setAttribute("headimg",headimg);
                            request.getSession().setAttribute("nickname",w.getNickname());

                            cookieController.addCookie(response,"headimg", headimg);
                            cookieController.addCookie(response,"nickname", w.getNickname());

                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }


        String shareid = request.getParameter("shareid");
        request.getSession().setAttribute("shareid", shareid);


        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setLimit(10);
        queryHelper.setOffset(0);
        List<Gokguessnum> goklist = baseService.listQueryForPage( "From Gokguessnum u order by u.create_time desc", Gokguessnum.class, queryHelper );

        JSONObject js = new JSONObject();
        JSONArray array = new JSONArray();

        model.addAttribute("chart", goklist );


        Juejinuser juejinuser = new Juejinuser();
        UsernameToken token = testService.getUser();
        if( token!= null ){
            juejinuser = testService.getJueUserById( token.getUserId().toString() );
            if( juejinuser == null ){
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
            }
        }else if( token == null ){
            // session显示未登录状态
            // 自动登录
            Cookie phoneCookie = cookieController.getCookieByName(request, "phone");
            if( phoneCookie != null ){
                String phone = phoneCookie.getValue();
                String passwd = testService.getPasswdByPhone( phone );
                if( !passwd.equals("") ){
                    SecurityUtils.getSubject().login(new UsernameToken(phone, passwd, (long) 0));
                }
            }
        }

        if( juejinuser != null ){
            model.addAttribute("user", juejinuser );
            model.addAttribute("money", juejinuser.getCoin().toString() );// 余额
            model.addAttribute("ifvip", juejinuser.getIfvip().toString() );// 是否vip
            model.addAttribute("star", juejinuser.getStar().toString() );// 获取几颗星
            model.addAttribute("knapsack", juejinuser.getKnapsack() );// 背包接口
            request.setAttribute( "userid", juejinuser.getId() );
            request.setAttribute( "token", juejinuser.getToken() );
        }

        // 朋友圈分享
        String url = "";
        if( request.getQueryString() == null ){
            url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
        }else{
            url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "?" + request.getQueryString();
        }
        long cur =  System.currentTimeMillis();
        Wxuser wxuser1 = testService.getWxByWxid( "gh_6dadebf53ec2" );
        Map<String, String> mapreq = new HashMap();
        String non = WXPayUtil.generateUUID();
        mapreq.put("noncestr", non);
        mapreq.put("jsapi_ticket", wxuser1.getTicket() );
        mapreq.put("timestamp", cur+"" );
        mapreq.put("url", url );
        String signStr = "";
        try {
            signStr = Funutil.generateSignature( mapreq );
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapreq.put("signature", signStr );
        String gsond = new Gson().toJson(mapreq);
        request.setAttribute( "signPackage", gsond );


        Cookie cookie = cookieController.getCookieByName(request, "ifnewbee3");
        if( cookie == null ){
            cookieController.addCookie(response,"ifnewbee3", "alredyshow");
            return "xs_animate";
        }else{
            return "index";
        }
    }


    @RequestMapping(value = "/channel",method = RequestMethod.GET)
    public String channel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 分享推广二维码
        UsernameToken token = testService.getUser();
        if(token != null ){
            tradeController.qrcode(request,response);
            String path = "/qrcode/"+token.getUserId()+".png";
            request.setAttribute( "qrcode_img", path );
        }
        return "channel";
    }

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String test(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "game";
    }
    @RequestMapping(value = "/test.do",method = RequestMethod.POST)
    public void test1(int count) {
        log.info(String.valueOf(count));
        log.info("test2的值");
    }

}
